<template>
	<el-tree
		lazy
		ref="tree"
		:props="props"
		node-key="id"
		show-checkbox
		check-strictly
		check-on-click-node
		:load="loadLibraryData"
		:expand-on-click-node="false"
		@node-click="handleNodeClick"
	></el-tree>
</template>

<script>
import { getResourceList } from '@/api/data/tbNetDisk';
import { getLibraryList } from '@/api/data/tbNetDiskDir';
export default {
	props: {
		value: { type: Object, default: () => {} },
		folderId: String
	},
	data() {
		return {
			checkedData: this.value,
			props: { label: 'name', children: 'zones', isLeaf: 'leaf' }
		};
	},
	watch: {
		value(data) {
			this.checkedData = data;
		},
		checkedData(data) {
			this.$emit('input', data);
		}
	},
	methods: {
		async loadLibraryData(node, resolve) {
			if (node.level === 0) {
				let result = await this.getLibraryData();
				let datas = result.map((item) => {
					return { ...item, disabled: item.id === this.folderId };
				});
				resolve(datas);
			} else if (node.level === 1) {
				let result = await this.getResourceData(node.data.id);
				let datas = result.map((item) => {
					return { ...item, name: item.oldName, disabled: item.id === this.folderId };
				});
				resolve(datas);
			} else {
				let result = await this.getResourceData(node.data.dirId, node.data.id);
				let datas = result.map((item) => {
					return { ...item, name: item.oldName, disabled: item.id === this.folderId };
				});
				resolve(datas);
			}
		},

		//获取资源库数据
		async getLibraryData() {
			let params = { page: 1, limit: 9999, type: 1 };
			let result = await getLibraryList(params).then((res) => res.data);
			if (result.code === '0') {
				return Promise.resolve(result.data || []);
			}
		},

		//资源请求参数
		formatRequestParams() {
			let params = { page: 1, limit: 9999 };
			params['isFolder'] = '1';
		},

		//获取资源数据
		async getResourceData(id, pid) {
			let params = { page: 1, limit: 9999, isFolder: '1', dirId: id, pId: pid || '0' };
			let result = await getResourceList(params).then((res) => res.data);
			if (result.code === '0') {
				return Promise.resolve(result.data || []);
			}
		},

		//选中库或文件夹
		handleNodeClick(data, node) {
			if (!node.checked) {
				this.checkedData = {};
			} else if (node.level === 1) {
				this.checkedData = { dirId: data.id, pid: '0' };
			} else {
				this.checkedData = { dirId: data.dirId, pid: data.id };
			}
			this.$refs['tree'].setCheckedKeys(node.checked ? [data.id] : []);
		}
	}
};
</script>

<style scoped>
.el-tree-node__expand-icon {
	font-size: 18px;
}
</style>
